﻿namespace DotRas
{
    using DotRas.Design;
    using pptpclient.Properties;
    using System;

    public sealed class RasSubEntryCollection : RasOwnedCollection<RasEntry, RasSubEntry>
    {
        internal RasSubEntryCollection(RasEntry owner) : base(owner)
        {
        }

        protected override void InsertItem(int index, RasSubEntry item)
        {
            if (item == null)
            {
                DotRas.ThrowHelper.ThrowArgumentNullException("item");
            }
            if (!base.IsInitializing && ((base.Owner == null) || (base.Owner.Owner == null)))
            {
                DotRas.ThrowHelper.ThrowInvalidOperationException(Resources.Exception_PhoneBookNotOpened);
            }
            item.Owner = base.Owner;
            if (base.IsInitializing)
            {
                base.InsertItem(index, item);
            }
            else if (RasHelper.SetSubEntryProperties(base.Owner.Owner, base.Owner, index, item))
            {
                base.InsertItem(index, item);
            }
        }

        internal void Load(RasPhoneBook phoneBook, int count)
        {
            if (phoneBook == null)
            {
                DotRas.ThrowHelper.ThrowArgumentNullException("phoneBook");
            }
            if (count <= 0)
            {
                DotRas.ThrowHelper.ThrowArgumentOutOfRangeException("count", count, Resources.Argument_ValueCannotBeLessThanOrEqualToZero);
            }
            try
            {
                base.BeginLock();
                base.IsInitializing = true;
                for (int i = 0; i < count; i++)
                {
                    RasSubEntry item = RasHelper.GetSubEntryProperties(phoneBook, base.Owner, i);
                    if (item != null)
                    {
                        base.Add(item);
                    }
                }
            }
            finally
            {
                base.IsInitializing = false;
                base.EndLock();
            }
        }

        protected override void RemoveItem(int index)
        {
            if (!base.IsInitializing && ((base.Owner == null) || (base.Owner.Owner == null)))
            {
                DotRas.ThrowHelper.ThrowInvalidOperationException(Resources.Exception_PhoneBookNotOpened);
            }
            if (base.IsInitializing)
            {
                base.RemoveItem(index);
            }
            else
            {
                base.RemoveItem(index);
            }
        }
    }
}

